package com.cci.kangdao.context;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.util.Log4jWebConfigurer;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.io.IOException;
import java.util.Properties;

public class Log4jlistener implements ServletContextListener {
    final static String LOG4J_HOME = "log4j.home";

    private static final String  projectconfig = "projectconfig.properties";
    private static Properties properties;

    @Override
    public void contextDestroyed(ServletContextEvent event) {
        Log4jWebConfigurer.shutdownLogging(event.getServletContext());
    }

    @Override
    public void contextInitialized(ServletContextEvent event) {
        String log4jHome = null;
        try{
            ClassPathResource cr = new ClassPathResource(projectconfig);
            if (properties == null) {
                properties = new Properties();
            }
            properties.load(cr.getInputStream());
            log4jHome = (String) properties.get(LOG4J_HOME);
        } catch (IOException ex ){

        } finally {
            if(StringUtils.isEmpty(log4jHome)){
                log4jHome = "logs";
            }
            System.setProperty(LOG4J_HOME, log4jHome);
            Log4jWebConfigurer.initLogging(event.getServletContext());
        }
    }
}
